/*
 * @Author: your name
 * @Date: 2021-06-24 14:08:27
 * @LastEditTime: 2021-10-15 15:12:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hbs\libs\tools\encrypt.ts
 */
const Crypto = require("crypto");
const sm2 = require('sm-crypto').sm2;

export default class {
    public static sha256 = (str, key) => {
        let hash = Crypto.createHmac('sha256', key).update(str, 'utf8').digest('hex');
        return hash;
    }
    public static md5 = (str) => {
        let md5 = Crypto.createHash('md5');
        let result = md5.update(str).digest('hex');
        return result;
    }
    /**
     * des加密 签名算法
     */
    public static desEncrypt = (message, key) => {

        key = key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length))
        const keyHex = Buffer.from(key)
        const cipher = Crypto.createCipheriv('des-cbc', keyHex, keyHex)
        let c = cipher.update(message.toString(), 'utf8', 'base64')
        c += cipher.final('base64')
        return c
    }

    /**
     * des解密 签名算法
     */
    public static desDecrypt = (text, key) => {
        let iv = key;
        key = key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length))
        iv = iv.length >= 8 ? iv.slice(0, 8) : iv.concat('0'.repeat(8 - iv.length))
        const keyHex = Buffer.from(key);
        const ivHex = Buffer.from(iv);
        const cipher = Crypto.createDecipheriv('des-cbc', keyHex, ivHex)
        let c = cipher.update(text, 'base64', 'utf8')
        c += cipher.final('utf8')
        return c;
    }
    /**
     * 微信的解密算法
     * @param appId 
     * @param sessionKey 
     * @param encryptedData 
     * @param iv 
     * @returns 
     */
    public static WX_desDecrypt = (sessionKey, encryptedData, iv) => {
        console.log(iv);
        sessionKey = Buffer.from(sessionKey, 'base64');
        encryptedData = Buffer.from(encryptedData, 'base64');
        iv = Buffer.from(iv, 'base64');
        // 解密
        var decipher = Crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
        // 设置自动 padding 为 true，删除填充补位
        decipher.setAutoPadding(true)
        var decoded = decipher.update(encryptedData, 'binary', 'utf8')
        decoded += decipher.final('utf8')
        decoded = JSON.parse(decoded)
        return decoded;
    }
    public static sm2Encrypt=(message,key="02a9fa092d95434eea7998ee6fa25a0abeda98496575685063608815fd9da1eb5c")=>{
        let ans=sm2.doEncrypt(message, key, 1);
        return ans;
    }
    public static sm2Decrypt(message,key="45057a186fd0f310ebfa86a559f56080e4d4631d766b09c07b9f8a5a52851257"){
        let ans=sm2.doDecrypt(message,key, 1)
        return ans;
    }
}